import React, { useState, useRef } from 'react';
import { history, connect } from 'umi';
import { Card, Button, Form } from 'antd';
import { Col, Row, Tag, Tooltip, Space, notification } from 'antd';
import { goodsType_status, expressPriceType as SelectTemplate } from '@/common/contact'
import DrawerCondition from '@/components/DrawerCondition';
import FormCondition from '@/components/FormCondition';
import EditorForm from '@/components/EditorForm';
import Sku from './components/Sku'
import aliOssUpload from '@/utils/aliOssUpload';
import PackagingModel from '@/components/PackagingModel'
import { useEffect } from 'react';
import ShareImage from '@/assert/image/shareImageCode.png';
import PopImgShow from '@/components/PopImgShow';
import moment from 'moment'
import './index.less'
const CodeInfo = (props) => {
  const { dispatch, onClose, loading, searchLoading } = props;
  const { location } = history;
  const { query } = location;
  const { id, handleType = 'edit' } = query
  const [data, setData] = useState([]);
  console.log(data.length, 123123)
  const [formData, setFormData] = useState({})
  const { content: oldData = '', expressPriceType = 'fix', showGoodsTagFlag = '1', expressType = 'express', buyLimitFlag = '0', upType = 'now', showFlag = '1', goodsSkuList = [], goodsPropertyList = [], goodsPackageList = [], commission: commissionInfo, helpWorkTypeAdminInfo = {},
    mainWorkTypeAdminInfo = {}, } = formData;
  const [form] = Form.useForm();
  const [MainAdminList, setMainAdminList] = useState([]);
  const [helpAdminList, sethelpAdminList] = useState([]);
  const EditContent = useRef(null);
  const [list, setList] = useState([]);
  const [content, setContent] = useState(oldData); // 输入的富文本内容
  const findParentIds = (data, childId, result = []) => {
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      if (item.id === childId) {
        result.push(item.id);
        if (item.parentId) {
          findParentIds(data, item.parentId, result);
        }
        break;
      } else if (item.subGoodsCategoryList) {
        findParentIds(item.subGoodsCategoryList, childId, result);
        if (result.length > 0 && item.id) {
          result.push(item.id);
          break;
        }
      }
    }
    return result;
  };

  const [showFlagSet, setShowFlag] = useState({
    showTag: showGoodsTagFlag,
    showbuyLimit: buyLimitFlag,
    showUpType: upType,
    expressPriceTypeSelect: expressPriceType,
    signFlag: '0'
  })
  const { showTag, showbuyLimit, showUpType, expressPriceTypeSelect, signFlag } = showFlagSet
  const ref = useRef(null)
  const packagingRef = useRef(null)
  // 新增修改 传id修改 不传id新增
  useEffect(() => {
    if (id) {
      dispatch({
        type: 'commodity/fetchOfflineGoodsDetail',
        payload: { goodsId: id },
        callback: (e) => {
          dispatch({
            type: 'commodity/fetchListGoodsCategory',
            callback: (listinfo) => {
              setList(listinfo);
              const {
                goodsBaseInfo = {},
                goodsPropertyList = [],
                goodsSkuList = [],
                goodsPackageList = [],

              } = e
              const { upDelayTime, signFlag, expressType, upType, categoryId, showGoodsTagFlag, buyLimitFlag, showFlag, expressPriceType } = goodsBaseInfo
              setFormData(
                {
                  ...goodsBaseInfo,
                  expressType: [expressType],
                  goodsPackageList,
                  goodsPropertyList: goodsPropertyList.map(item => {
                    const {
                      propertyCover,
                      propertyName,
                      propertyValue = ''
                    } = item
                    return {
                      showImage: propertyCover ? ['add'] : '',
                      image: propertyCover,
                      name: propertyName,
                      valueList: propertyValue.split(',').map(val => {
                        return {
                          value: val
                        }
                      })
                    }
                  }),
                  goodsSkuList: goodsSkuList.map(item => {
                    const { propertyDesc = '' } = item
                    return {
                      ...item,
                      properties: propertyDesc.split(',').map(val => {
                        let property = val.split(':')
                        return {
                          name: property[0],
                          value: property[1]
                        }
                      })
                    }
                  }),
                  categoryId: findParentIds(listinfo, Number(categoryId)).reverse(),
                  upDelayTime: upType === 'delay' ? moment(upDelayTime) : ''
                }
              )
              if (id) {

                form.setFieldsValue({
                  showTag: showGoodsTagFlag,
                  showbuyLimit: buyLimitFlag,
                  showUpType: upType,
                  showFlag: showFlag,
                })
              }
              setShowFlag({
                showTag: showGoodsTagFlag,
                showbuyLimit: buyLimitFlag,
                showUpType: upType,
                expressPriceTypeSelect: expressPriceType,
              })
            },
          });

        }
      })
    }
    else {
      fetchData();
    }
  }, []);
  console.log(formData)
  const fetchRoleEdit = () => {
    let goodsSkuList = ref.current.getRowData()
    let goodsPropertyList = ref.current.getPropertyList()
    let goodsPackageList = packagingRef.current.getPackaging()
    let flag = goodsSkuList.reduce((item, val) => {
      if (!item) {
        return item
      }
      else {
        if (!val.price || !val.stock) {
          return false
        }
        else {
          return item
        }
      }

    }, true)
    let property = goodsPropertyList.reduce((item, val) => {
      if (!item) {
        return item
      }
      else {
        if (!val.valueList || !val.name) {
          return false
        }
        else {
          return item
        }
      }

    }, true)
    let goodsPackageFlag = goodsPackageList.reduce((item, val) => {
      if (!item) {
        return item
      }
      else {
        if (val.chooseType === 'any' && (!val.chooseAmount || val.chooseAmount === 0)
        ) {
          console.log(val)
          notification.warning({
            message: '错误提示',
            description: `${goodsType_status[val.packageGoodsType
            ]} 选择任何后 打包数量不能为0`,
          });
          return false
        }
        else {
          return item
        }
      }

    }, true)
    if (!goodsPackageFlag) {
      return
    }
    else if (!flag) {
      return notification.warning({
        message: '错误提示',
        description: '库存或价格不能为0',
      });
    } else if (!property) {
      return notification.warning({
        message: '错误提示',
        description: '规格名称不能为空并且规格值不能为空',
      });
    } else {
      goodsSkuList = goodsSkuList.map(item => {
        return {
          ...item,
          propertyDesc: item.properties.map((val, o) => {
            return val.name + ':' + val.value
          }).toString()
        }
      })
      goodsPropertyList = goodsPropertyList.map(item => {
        const { name, image, valueList } = item
        return {
          propertyName: name,
          propertyCover: image,
          propertyValue: valueList.map(val => { return val.value }).toString()
        }
      })
      form.validateFields().then(async (values) => {
        const { coverVideo, picture, buyLimitFlag = [], categoryId, upDelayTime, upType, expressType } = values
        let video = await aliOssUpload(coverVideo)
        let img = await aliOssUpload(picture)
        let buyLimit = buyLimitFlag.toString()
        let category = categoryId[categoryId.length - 1]
        let data = {
          id,
          goodsBaseInfo: {
            id,
            ...values,
            content,
            coverVideo: video.toString(),
            picture: img.toString(),
            buyLimitFlag: buyLimit,
            categoryId: category,
            priceType: 'money',
            upDelayTime: upType === 'delay' ? moment(upDelayTime).format('YYYY-MM-DD HH:mm:ss') : '',
            expressType: expressType.toString(),
          },
          goodsSkuList,
          goodsPropertyList,
          goodsPackageList
        }
        dispatch({
          type: 'commodity/fakeSaveOfflineGoods',
          payload: data,
          callback: () => {
            history.goBack()
          }
        })
      })
    }
  };
  const fetchData = () => {
    dispatch({
      type: 'commodity/fetchListGoodsCategory',
      callback: (e) => {
        setList(e);
      },
    });
  };

  useEffect(() => {
    if (id && formData.id) {
      EditContent.current.reloadEdit();
    }

  }, [formData]);
  const filterList = (list) => {
    return list.map((item) => {
      const { categoryName: label, id: value, subGoodsCategoryList: children } = item;
      const localItem = {
        label,
        value,
        node: item['node'],
        children: children ? filterList(children) : undefined,
      };
      return localItem;
    });
  };

  const formItems = [
    {
      label: '商品名称',
      name: 'goodsName',
    },
    {
      label: '商品类目',
      name: 'categoryId',
      type: 'cascader',
      select: filterList(list),
    },
    {
      label: '商品图片',
      name: 'picture',
      type: 'upload',
      extra: '建议尺寸1：1，JPG、PNG格式， 图片小于5M，你可以拖拽图片调整顺序，最多上传15张 ',
      maxFile: 15
    },
    {
      label: '主图视频',
      name: 'coverVideo',
      rules: [{ required: false }],
      extra: '视频画面建议尺寸1:1或16:9，时长10-30s，默认优先展示主图视频',
      type: 'videoUpload',
      maxFile: 1
    },
    {
      label: '商品明细',
      name: 'goodsDesc',
      type: 'textArea',
      rules: [{ required: false }],
      placeholder: '商品对应内容'
    },
    {
      type: 'noForm',
      formItem: (
        <Row>
          <Col span={6} style={{ textAlign: 'right' }} className="">商品详情：</Col>
          <Col span={17} className="">
            <EditorForm
              ref={EditContent}
              initEditor={id ? false : true}
              content={oldData} editCallback={(val) => setContent(val)}></EditorForm></Col>
        </Row>
      ),
    },


  ];
  const formItemsGroup1 = [
    {
      label: '是否展示实物商品标签',
      name: 'showGoodsTagFlag',
      type: 'radio',
      onChange: (e) => {
        setShowFlag({
          ...showFlagSet,
          showTag: e.target.value
        })
      },
      select: {
        1: '展示',
        0: '不展示',
      }
    },
    {
      label: '商品标签',
      name: 'goodsTag',
      visible: showTag != '1' ? false : true,
      maxLength: 6
    },
    {
      type: 'noForm',

      rules: [{ required: false }],
      formItem: <Sku form={form} goodsSkuList={goodsSkuList} formData={formData} goodsPropertyList={goodsPropertyList} setData={setData} propsRef={ref} data={data}></Sku>,
    },
    {
      label: '重量（kg）',
      visible: data.length === 0,
      name: 'weight',
      rules: [{ required: false }],
      type: 'number',
    },
    {
      label: '售价',
      name: 'price',
      type: 'number',
      rules: [
        { required: true },
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      disabled: data.length > 0
    },
    {
      label: '库存',
      name: 'stock',
      type: 'number',
      disabled: data.length > 0
    },
    {
      label: '底价',
      type: 'number',
      rules: [
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      name: 'oriPrice',
    },
    {
      label: '商品编码',
      rules: [{ required: false }],
      name: 'goodsCode',
    },

  ]
  const formItemsGroup2 = [
    {
      label: '快递类型',
      name: 'expressType',
      select: [{
        label: '物流快递',
        value: 'express',
        disabled: true
      }, {
        label: '到店自提',
        value: 'takeSelf',
        disabled: true
      }],
      type: 'checkbox'
    },
    {
      label: '快递运费',
      name: 'expressPriceType',
      type: 'radio',
      onChange: (e) => {
        setShowFlag({
          ...showFlagSet,
          expressPriceTypeSelect: e.target.value
        })
      },
      select: SelectTemplate
    },
    {
      label: '统一邮费',
      name: 'expressPrice',
      visible: expressPriceTypeSelect === 'fix'
    },
    {
      label: '运费模板',
      name: 'expressTemplateId',
      visible: expressPriceTypeSelect !== 'fix',
      type: 'expressTemplate'
    },
  ]
  const formItemsGroup3 = [
    {
      type: 'noForm',
      formItem: (
        <PackagingModel defaultDataList={goodsPackageList} ref={packagingRef} detail={formData}> </PackagingModel>
      ),
    },
    {
      label: '限购设置',
      name: 'buyLimitFlag',
      rules: [{ required: false }],
      select: [{
        label: '限购',
        value: '1',
      }],
      onChange: (e) => {
        setShowFlag({
          ...showFlagSet,
          showbuyLimit: e.toString()
        })
      },
      type: 'checkbox'
    },
    {
      label: '限制每人可购买数量',
      name: 'buyLimit',
      type: 'number',
      rules: showbuyLimit !== '1' ? [{ required: false }] : [{ required: true }],
      disabled: showbuyLimit !== '1'
    },
  ]
  const formItemsGroup4 = [
    {
      label: '上架类型',
      name: 'upType',
      type: 'radio',
      onChange: (e) => {
        setShowFlag({
          ...showFlag,
          showUpType: e.target.value
        })
      },
      select: {
        now: '立刻上架',
        delay: '定时上架',
        off: '暂不上架'
      }
    },
    {
      label: '定时上架时间',
      name: 'upDelayTime',
      type: 'dataPicker',
      format: 'YYYY-MM-DD HH:mm',
      visible: showUpType === 'delay'
    },
    {
      label: '是否显示在店铺',
      name: 'showFlag',
      type: 'radio',
      select: {
        0: '否',
        1: '是',
      },
    },
  ]
  return (
    <Card title={id ? '编辑商品' : '新建商品'} style={{ position: 'relative' }}>
      <div className='commodity-manage-part'>
        <div className='commodity-part-title'>
          <div className='commodity-title-line'></div>
          <div className='commodity-part-title-word'>基本信息</div>
        </div>
      </div>
      <FormCondition form={form} formItems={formItems} initialValues={formData}></FormCondition>
      <div className='commodity-manage-part'>
        <div className='commodity-part-title'>
          <div className='commodity-title-line'></div>
          <div className='commodity-part-title-word'>商品信息</div>
        </div>
      </div>
      <FormCondition form={form} formItems={formItemsGroup3} initialValues={formData}></FormCondition>
      <div className='commodity-manage-part'>
        <div className='commodity-part-title'>
          <div className='commodity-title-line'></div>
          <div className='commodity-part-title-word'>商品标签</div>
        </div>
      </div>
      <FormCondition form={form} formItems={formItemsGroup1} initialValues={{ ...formData, expressType: ["express"], expressPriceType }}></FormCondition>
      <div className='commodity-manage-part'>
        <div className='commodity-part-title'>
          <div className='commodity-title-line'></div>
          <div className='commodity-part-title-word'>物流</div>
        </div>
      </div>
      <FormCondition form={form} formItems={formItemsGroup2} initialValues={{ ...formData, expressPriceType: expressPriceTypeSelect }}></FormCondition>
      <div className='commodity-manage-part'>
        <div className='commodity-part-title'>
          <div className='commodity-title-line'></div>
          <div className='commodity-part-title-word'>上架设置</div>
        </div>
      </div>
      <FormCondition form={form} formItems={formItemsGroup4} initialValues={{ ...formData, upType, showFlag }}></FormCondition>
      <div className="create_upload_btn">
        <Button onClick={() => fetchRoleEdit()} type="primary">
          {id ? '保存' : '创建商品'}
        </Button>
      </div>
    </Card>


  );
};
export default connect(({ loading }) => ({
  loading: loading.effects['commodity/fakeSaveOfflineGoods'],
}))(CodeInfo);
